package com.gh.lucene.search;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;

import annotationDemo.Book;

import com.hunter.lucene.util.Lucenes;
import com.hunter.lucene.util.config.ConfigLoadException;
import com.hunter.lucene.util.config.Configuration;
import com.hunter.lucene.util.config.LuceneException;
import com.hunter.lucene.util.config.validation.ConfigInfoInvalideException;
import com.hunter.lucene.util.index.IndexException;
import com.hunter.lucene.util.index.Writable;

public class OpenSearchBeforeWrite {
	public static void main(String[] args) throws IOException,
			ConfigLoadException, ConfigInfoInvalideException, IndexException, LuceneException {
		Directory directory = Lucenes.getSimpleFileSystemDirectory("E:\\index");
		IndexReader indexReader = IndexReader.open(directory, true);
		IndexSearcher searcher = new IndexSearcher(indexReader);
		Term term = new Term("name", "renjie");
		TermQuery query = new TermQuery(term);
		TopDocs docs = searcher.search(query, 100);
		for (ScoreDoc doc : docs.scoreDocs) {
			int id = doc.doc;
			Document document = searcher.doc(id);
			System.out.println(document.getField("name").stringValue());
		}

		Configuration configuraiton = Configuration.build();
		Writable writer = configuraiton.getOrBuildWriter();
		Book book = new Book();
		book.setName("renjie");
		//writer.add(book);
		//writer.commit();

		searcher = new IndexSearcher(indexReader.reopen());
		docs = searcher.search(query, 100);
		for (ScoreDoc doc : docs.scoreDocs) {
			int id = doc.doc;
			Document document = searcher.doc(id);
			System.out.println(document.getField("name").stringValue());
		}

		writer.close();
	}
}
